import 'package:flame/components.dart';
import 'package:flame/extensions.dart';

import 'Tank.dart';

class BulletTank extends PositionComponent {
  late final double speed;
  late double myAngle;
  bool isLive = true;
  late Sprite blueSprite;
  late TankID id;
  bool isHit = false;
  late Offset offset;
  late Vector2 screenSize;

  BulletTank(
      {required this.speed,
      required this.offset,
      required this.myAngle,
      required this.id,
      required this.screenSize}) {
    init();
  }

  void init() async {
    //add(RectangleHitbox()..debugMode = true);
    var url = TankBullet[id];
    blueSprite = await Sprite.load('$url');
    position.setValues(offset.dx, offset.dy);
  }

  @override
  void update(double dt) {
    if (isHit) {
      removeFromParent();
      return;
    }
    if (!isLive) {
      removeFromParent();
      return;
    }
    super.update(dt);
    position = position + Offset.fromDirection(myAngle, speed * dt).toVector2();
    if (!screenSize.toSize().contains(position.toOffset())) {
      isLive = false;
    }
  }

  @override
  void render(Canvas canvas) {
    if (isHit) {
      removeFromParent();
      return;
    }
    if (!isLive) {
      removeFromParent();
      return;
    }
    super.render(canvas);
    canvas.save();
    canvas.translate(position.x, position.y); //(offset.dx, offset.dy);
    canvas.rotate(myAngle);
    blueSprite.renderRect(canvas, const Rect.fromLTWH(-4, -2, 8, 4));
    canvas.restore();
  }
}
